package com.sf.fy.uav.applet.config;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.sf.fy.uav.applet.order.controller.OrderController;
import com.sf.fy.uav.applet.order.controller.task.TaskController;
import com.sf.fy.uav.applet.order.service.OrderService;
import com.sf.fy.uav.common.enums.ActivityProductTypeEnum;
import com.sf.fy.uav.common.enums.OrderStatusEnum;
import com.sf.fy.uav.common.enums.ServicePrefixEnum;
import com.sf.fy.uav.common.request.common.IdRequest;
import com.sf.fy.uav.common.utils.PhoneEncoderUtil;
import com.sf.fy.uav.common.utils.RedisPrefixKey;
import com.sf.fy.uav.entity.ErrandOrder;
import com.sf.fy.uav.mapper.ErrandOrderMapper;
import com.sf.fy.uav.order.controller.*;
import com.sf.fy.uav.order.entity.Pricing;
import com.sf.fy.uav.rest.SysTcRest;
import com.sf.fy.uav.utils.AirportInfoUtils;
import com.sf.fy.uav.order.entity.CityAirport;
import com.sf.fy.uav.order.entity.OrderExtra;
import com.sf.fy.uav.order.entity.OrderInfo;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.time.Duration;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;

import com.sf.fy.uav.sms.rest.SendSmsRest;
import com.sf.fy.uav.order.mapper.OrderInfoMapper;
import org.springframework.util.StringUtils;

/**
 * @author LTQ
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class DelayQueue {


    @Value("${redis.dead:delayQueue}")
    private String DELAY_MESSAGE_QUEUE;

    private static SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    private final RedisTemplate<String, String> redisTemplate;


    @Autowired
    private RedissonClient redissonClient;

    @Autowired
    private TaskController taskController;

    @Autowired
    private OrderController orderController;

    private final SysTcRest sysTcRest;

    @Autowired
    private ErrandOrderMapper errandOrderMapper;

    @Autowired
    private OrderInfoRest orderInfoRest;

    @Autowired
    private ErrandOrderRest errandOrderRest;

    @Autowired
    private OrderService orderService;

    @Autowired
    private PhoneEncoderUtil phoneEncoderUtil;

    @Autowired
    private CityAirportRest cityAirportRest;

    @Autowired
    private SendSmsRest sendSmsRest;

    @Autowired
    private AirportInfoUtils airportInfoController;

    @Value("${sms.pending-items-template-code:DING-DAN-CHAO-SHI-WEI-JIE-DAN-TI-XING}")
    private String pendingItemsTemplateCode;

    @Value("${sms.door-to-door-pickup-down-template-code:DING-DAN-CHAO-SHI-WEI-SHANG-MEN-QU-HUO-TI-XING}")
    private String doorToDoorPickupDownTemplateCode;

    @Value("${sms.drone-has-been-picked-up-template-code:DING-DAN-WU-REN-JI-CHAO-SHI-WEI-QI-FEI-TI-XING}")
    private String droneHasBeenPickedUpTemplateCode;
    @Value("${sms.drone-delivery-in-progress-template-code:DING-DAN-WU-REN-JI-CHAO-SHI-WEI-CHU-LI-JIANG-LUO-TI-XING}")
    private String droneDeliveryInProgressTemplateCode;
    @Value("${sms.to-be-dispatched-template-code:DING-DAN-CHAO-SHI-WEI-PAI-SONG-WAN-CHENG-TI-XING}")
    private String toBeDispatchedTemplateCode;

    @Autowired
    private OrderInfoMapper orderInfoMapper;

    @Autowired
    private PricingRest pricingRest;

    @Autowired
    private OrderExtraController orderExtraController;

    /**
     * 消息入队
     * 只要用户继续发起请求，就会继续延长时间戳的时间 直到用户一直没有请求后，然后到达指定时间给消费者进行消费
     * 如果有其他用户进来，那么这个队列会根据时间戳进行排序 排在前面的并且达到指定时间就先进行消费
     *
     * @param msg
     * @param time
     */
    public void pushQueue(String msg, Long time) {
        try {
            // 存的值是集合的主键 一般固定
            // 第二个是id 每个用户一个id
            // 第三个是根据什么进行排序，这里是根据时间戳，这里如果是同个key，那么会刷新同个key的时间戳并重新进行排序
            // 不同的key就是当前时间加10秒，也就是10秒后过期
            log.info("生产了消息" + msg + "生产时间 " + simpleDateFormat.format(System.currentTimeMillis()));
            redisTemplate.opsForZSet().add(ServicePrefixEnum.SAME_CITY + "." + DELAY_MESSAGE_QUEUE, msg, System.currentTimeMillis() + time);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 消息入队
     * 只要用户继续发起请求，就会继续延长时间戳的时间 直到用户一直没有请求后，然后到达指定时间给消费者进行消费
     * 如果有其他用户进来，那么这个队列会根据时间戳进行排序 排在前面的并且达到指定时间就先进行消费
     *
     * @param msg
     * @param time
     */
    public void pushQueue2(String msg, Long time) {
        try {
            // 存的值是集合的主键 一般固定
            // 第二个是id 每个用户一个id
            // 第三个是根据什么进行排序，这里是根据时间戳，这里如果是同个key，那么会刷新同个key的时间戳并重新进行排序
            // 不同的key就是当前时间加10秒，也就是10秒后过期
            log.info("生产了消息" + msg + "生产时间 " + simpleDateFormat.format(System.currentTimeMillis()));
            redisTemplate.opsForZSet().add(ServicePrefixEnum.SAME_CITY + "." + DELAY_MESSAGE_QUEUE, msg, time);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 消息出队
     * 权重就是时间戳
     */
    @Scheduled(cron = "0/5 * * * * ?")
    public void pullQueue() {
        System.out.println("------------等待消费--------------" + simpleDateFormat.format(System.currentTimeMillis()));
        // 获取0-当前时间戳的范围的所有值
        Set<String> set = redisTemplate.opsForZSet().rangeByScore(ServicePrefixEnum.SAME_CITY + "." + DELAY_MESSAGE_QUEUE, 0, System.currentTimeMillis());
        Iterator<String> iterator = set.iterator();
        while (iterator.hasNext()) {
            String value = iterator.next();
            if (value.startsWith(ServicePrefixEnum.SAME_CITY.name())) {
                // 遍历取出每一个score
                Double score = redisTemplate.opsForZSet().score(ServicePrefixEnum.SAME_CITY + "." + DELAY_MESSAGE_QUEUE, value);
                if (!ObjectUtils.isEmpty(score)) {
                    // 达到时间进行消费 当前时间大于
                    if (System.currentTimeMillis() > score) {
                        if (!value.contains(ServicePrefixEnum.SAME_CITY + RedisPrefixKey.UPDATE_RIDER_COORDINATES) && !value.contains(ServicePrefixEnum.SAME_CITY + RedisPrefixKey.SEND_FS_NOTICE) && !value.contains(ServicePrefixEnum.SAME_CITY + RedisPrefixKey.SEND_FS_OVERTIME_WARNING_NOTICE) && !value.contains(ServicePrefixEnum.SAME_CITY + RedisPrefixKey.SEND_FS_OVERTIME_NOTICE) && !value.contains(ServicePrefixEnum.SAME_CITY + RedisPrefixKey.SEND_NEW_ORDER_FS_MSG)) {
                            // 移除该队列的值,避免重复消费
                            redisTemplate.opsForZSet().remove(ServicePrefixEnum.SAME_CITY + "." + DELAY_MESSAGE_QUEUE, value);
                        }
                        if (value.contains(ServicePrefixEnum.SAME_CITY + RedisPrefixKey.ORDER_COUNT_DOWN)) {
                            log.info("消费了" + value + "消费时间 " + simpleDateFormat.format(System.currentTimeMillis()));
                            String orderId = value.replace(ServicePrefixEnum.SAME_CITY + RedisPrefixKey.ORDER_COUNT_DOWN, "");
                            //订单支付倒数结束
                            IdRequest idRequest = new IdRequest();
                            idRequest.setId(orderId);
                            taskController.expireOrder(idRequest);
                        } else if (value.contains(ServicePrefixEnum.SAME_CITY + RedisPrefixKey.PENDING_ITEMS_DOWN) || value.contains(ServicePrefixEnum.SAME_CITY + RedisPrefixKey.DOOR_TO_DOOR_PICKUP_DOWN) || value.contains(ServicePrefixEnum.SAME_CITY + RedisPrefixKey.DRONE_HAS_BEEN_PICKED_UP_DOWN) || value.contains(ServicePrefixEnum.SAME_CITY + RedisPrefixKey.DRONE_DELIVERY_IN_PROGRESS_DOWN) || value.contains(ServicePrefixEnum.SAME_CITY + RedisPrefixKey.TO_BE_DISPATCHED_DOWN)) {
                            log.info("消费了" + value + "消费时间 " + simpleDateFormat.format(System.currentTimeMillis()));
                            String orderId = "";
                            String templateCode = "";
                            OrderInfo orderInfo = null;
                            if (value.contains(ServicePrefixEnum.SAME_CITY + RedisPrefixKey.PENDING_ITEMS_DOWN)) {
                                orderId = value.replace(ServicePrefixEnum.SAME_CITY + RedisPrefixKey.PENDING_ITEMS_DOWN, "");
                                orderInfo = orderInfoMapper.selectById(orderId);
                                if (!OrderStatusEnum.PENDING_ITEMS.getStatus().equals(orderInfo.getOrderStatus())) {
                                    continue;
                                }
                                templateCode = pendingItemsTemplateCode;
                            } else if (value.contains(ServicePrefixEnum.SAME_CITY + RedisPrefixKey.DOOR_TO_DOOR_PICKUP_DOWN)) {
                                orderId = value.replace(ServicePrefixEnum.SAME_CITY + RedisPrefixKey.DOOR_TO_DOOR_PICKUP_DOWN, "");
                                orderInfo = orderInfoMapper.selectById(orderId);
                                if (!OrderStatusEnum.DOOR_TO_DOOR_PICKUP.getStatus().equals(orderInfo.getOrderStatus())) {
                                    continue;
                                }
                                templateCode = doorToDoorPickupDownTemplateCode;
                            } else if (value.contains(ServicePrefixEnum.SAME_CITY + RedisPrefixKey.DRONE_HAS_BEEN_PICKED_UP_DOWN)) {
                                orderId = value.replace(ServicePrefixEnum.SAME_CITY + RedisPrefixKey.DRONE_HAS_BEEN_PICKED_UP_DOWN, "");
                                orderInfo = orderInfoMapper.selectById(orderId);
                                if (!OrderStatusEnum.DRONE_HAS_BEEN_PICKED_UP.getStatus().equals(orderInfo.getOrderStatus())) {
                                    continue;
                                }
                                templateCode = droneHasBeenPickedUpTemplateCode;
                            } else if (value.contains(ServicePrefixEnum.SAME_CITY + RedisPrefixKey.DRONE_DELIVERY_IN_PROGRESS_DOWN)) {
                                orderId = value.replace(ServicePrefixEnum.SAME_CITY + RedisPrefixKey.DRONE_DELIVERY_IN_PROGRESS_DOWN, "");
                                orderInfo = orderInfoMapper.selectById(orderId);
                                if (!OrderStatusEnum.DRONE_DELIVERY_IN_PROGRESS.getStatus().equals(orderInfo.getOrderStatus())) {
                                    continue;
                                }
                                templateCode = droneDeliveryInProgressTemplateCode;
                            } else if (value.contains(ServicePrefixEnum.SAME_CITY + RedisPrefixKey.TO_BE_DISPATCHED_DOWN)) {
                                orderId = value.replace(ServicePrefixEnum.SAME_CITY + RedisPrefixKey.TO_BE_DISPATCHED_DOWN, "");
                                orderInfo = orderInfoMapper.selectById(orderId);
                                if (!OrderStatusEnum.TO_BE_DISPATCHED.getStatus().equals(orderInfo.getOrderStatus())) {
                                    continue;
                                }
                                templateCode = toBeDispatchedTemplateCode;
                            }

                            OrderExtra orderExtra = orderExtraController.getByOrderId(orderId);
                            if (!ObjectUtils.isEmpty(orderInfo)) {
                                String takeoffConnId = orderInfo.getTakeoffConnId();
                                String landingConnId = orderInfo.getLandingConnId();
                                if (!StringUtils.isEmpty(takeoffConnId) && !StringUtils.isEmpty(landingConnId) && !ObjectUtils.isEmpty(orderExtra)) {
                                    CityAirport takeoffCityAirport = cityAirportRest.selectByConnId(takeoffConnId);
                                    CityAirport landingCityAirport = cityAirportRest.selectByConnId(landingConnId);
                                    String place = "";
                                    String phone = "";
                                    if (value.contains(ServicePrefixEnum.SAME_CITY + RedisPrefixKey.PENDING_ITEMS_DOWN)) {
                                        place = takeoffCityAirport.getName();
                                        phone = orderExtra.getFySenderTel();
                                    } else if (value.contains(ServicePrefixEnum.SAME_CITY + RedisPrefixKey.DOOR_TO_DOOR_PICKUP_DOWN)) {
                                        place = takeoffCityAirport.getName();
                                        phone = orderExtra.getFySenderTel();
                                    } else if (value.contains(ServicePrefixEnum.SAME_CITY + RedisPrefixKey.DRONE_HAS_BEEN_PICKED_UP_DOWN)) {
                                        place = takeoffCityAirport.getName();
                                        phone = orderExtra.getFySenderTel();
                                    } else if (value.contains(ServicePrefixEnum.SAME_CITY + RedisPrefixKey.DRONE_DELIVERY_IN_PROGRESS_DOWN)) {
                                        place = landingCityAirport.getName();
                                        phone = orderExtra.getFyReceiverTel();
                                    } else if (value.contains(ServicePrefixEnum.SAME_CITY + RedisPrefixKey.TO_BE_DISPATCHED_DOWN)) {
                                        place = landingCityAirport.getName();
                                        phone = orderExtra.getFyReceiverTel();
                                    }
                                    phone = phoneEncoderUtil.decryptString(phone);
                                    sendSmsRest.sendNotice(phone, templateCode, orderInfo.getTcWaybillNo(), place);
                                }
                            }

                        } else if (value.contains(ServicePrefixEnum.SAME_CITY + RedisPrefixKey.SEND_NOTICE)) {
                            log.info("消费了" + value + "消费时间 " + simpleDateFormat.format(System.currentTimeMillis()));
                            String orderId = value.replace(ServicePrefixEnum.SAME_CITY + RedisPrefixKey.SEND_NOTICE, "");
                            orderService.sendPaySuccessMsg(orderId);
                        } else if (value.contains(ServicePrefixEnum.SAME_CITY + RedisPrefixKey.RECORD_AIR_PORT)) {
                            log.info("消费了" + value + "消费时间 " + simpleDateFormat.format(System.currentTimeMillis()));
                            String[] longitudeAndLatitude = value.replace(ServicePrefixEnum.SAME_CITY + RedisPrefixKey.RECORD_AIR_PORT, "").split("_");
                            if (longitudeAndLatitude.length == 3) {
                                String uuid = longitudeAndLatitude[0];
                                double longitude = Double.parseDouble(longitudeAndLatitude[1]);
                                double latitude = Double.parseDouble(longitudeAndLatitude[2]);
                                airportInfoController.obtainTheNearestTerminalWithinTheRange(uuid, longitude, latitude);
                            }
                        }
                    }
                }
            }

        }
    }


    /**
     * 消息出队
     * 权重就是时间戳
     */
//    @Scheduled(cron = "0/5 * * * * ?")
    public void pullQueuePer5Seconds() {
        Lock lock = null;
        try {
            lock = redissonClient.getLock(ServicePrefixEnum.SAME_CITY + RedisPrefixKey.SCHEDULED_TASKS_3);
            boolean b = lock.tryLock(5, TimeUnit.SECONDS);
            if (b) {
                System.out.println("------------等待消费--------------" + simpleDateFormat.format(System.currentTimeMillis()));
                // 获取0-当前时间戳的范围的所有值
                Set<String> set = redisTemplate.opsForZSet().rangeByScore(ServicePrefixEnum.SAME_CITY + "." + DELAY_MESSAGE_QUEUE, 0, System.currentTimeMillis());
                Iterator<String> iterator = set.iterator();
                while (iterator.hasNext()) {
                    String value = iterator.next();
                    if (value.startsWith(ServicePrefixEnum.SAME_CITY.name())) {
                        // 遍历取出每一个score
                        Double score = redisTemplate.opsForZSet().score(ServicePrefixEnum.SAME_CITY + "." + DELAY_MESSAGE_QUEUE, value);
                        if (!ObjectUtils.isEmpty(score)) {
                            // 达到时间进行消费 当前时间大于
                            if (System.currentTimeMillis() > score) {
                                log.info("消费了" + value + "消费时间 " + simpleDateFormat.format(System.currentTimeMillis()));
                                if (value.contains(ServicePrefixEnum.SAME_CITY + RedisPrefixKey.SEND_FS_NOTICE)) {
                                    String orderId = value.replace(ServicePrefixEnum.SAME_CITY + RedisPrefixKey.SEND_FS_NOTICE, "");
                                    OrderInfo orderInfo = orderInfoMapper.selectById(orderId);
                                    if (!ObjectUtils.isEmpty(orderInfo)) {
                                        if (orderInfo.getOrderStatus().equals(OrderStatusEnum.PENDING_ITEMS.getStatus())) {
                                            //去提醒
                                            orderService.sendFsNoticeMsg(orderId);
                                        } else {
                                            // 移除该队列的值,避免重复消费
                                            redisTemplate.opsForZSet().remove(ServicePrefixEnum.SAME_CITY + "." + DELAY_MESSAGE_QUEUE, value);
                                        }
                                    } else {
                                        // 移除该队列的值,避免重复消费
                                        redisTemplate.opsForZSet().remove(ServicePrefixEnum.SAME_CITY + "." + DELAY_MESSAGE_QUEUE, value);
                                    }
                                } else if (value.contains(ServicePrefixEnum.SAME_CITY + RedisPrefixKey.SEND_NEW_ORDER_FS_MSG)) {

                                    String orderId = value.replace(ServicePrefixEnum.SAME_CITY + RedisPrefixKey.SEND_NEW_ORDER_FS_MSG, "");

                                    //去提醒
                                    orderService.sendNewOrderFsNoticeMsg(orderId);
                                    // 移除该队列的值,避免重复消费
                                    redisTemplate.opsForZSet().remove(ServicePrefixEnum.SAME_CITY + "." + DELAY_MESSAGE_QUEUE, value);


                                } else if (value.contains(ServicePrefixEnum.SAME_CITY + RedisPrefixKey.SEND_FS_OVERTIME_WARNING_NOTICE)) {
                                    String orderId = value.replace(ServicePrefixEnum.SAME_CITY + RedisPrefixKey.SEND_FS_OVERTIME_WARNING_NOTICE, "");
                                    OrderInfo orderInfo = orderInfoMapper.selectById(orderId);
                                    List<Pricing> pricingList = pricingRest.getByProductTypes(Arrays.asList(ActivityProductTypeEnum.LOCAL.getCode(), ActivityProductTypeEnum.CROSS_REGION.getCode()));

                                    if (!ObjectUtils.isEmpty(orderInfo)) {
                                        Integer orderStatus = orderInfo.getOrderStatus();
                                        Byte orderType = orderInfo.getOrderType();
                                        // 计算时间差
                                        Duration duration = Duration.between(orderInfo.getUpdateTime().toInstant(), new Date().toInstant());
                                        // 输出相差的分钟数
                                        long minutes = duration.toMinutes();
                                        if (orderStatus.equals(OrderStatusEnum.COMPLETED.getStatus()) || orderStatus.equals(OrderStatusEnum.CANCEL.getStatus())) {
                                            //已完成或者已经取消的就不用提醒了
                                            // 移除该队列的值,避免重复消费
                                            redisTemplate.opsForZSet().remove(ServicePrefixEnum.SAME_CITY + "." + DELAY_MESSAGE_QUEUE, value);
                                        } else {
                                            if (!ObjectUtils.isEmpty(orderType)) {
                                                pricingList.forEach(pricing -> {
                                                    if (orderType.equals(pricing.getProductType())) {
                                                        if (minutes >= pricing.getTimeoutWarningTime()) {
                                                            //去提醒
                                                            orderService.sendFsOvertimeWarningNoticeMsg(orderId);
                                                            // 移除该队列的值,避免重复消费
                                                            redisTemplate.opsForZSet().remove(ServicePrefixEnum.SAME_CITY + "." + DELAY_MESSAGE_QUEUE, value);
                                                        }
                                                    }
                                                });

                                            }

                                        }
                                    }

                                } else if (value.contains(ServicePrefixEnum.SAME_CITY + RedisPrefixKey.SEND_FS_OVERTIME_NOTICE)) {
                                    String orderId = value.replace(ServicePrefixEnum.SAME_CITY + RedisPrefixKey.SEND_FS_OVERTIME_NOTICE, "");
                                    OrderInfo orderInfo = orderInfoMapper.selectById(orderId);
                                    if (!ObjectUtils.isEmpty(orderInfo)) {
                                        List<Pricing> pricingList = pricingRest.getByProductTypes(Arrays.asList(ActivityProductTypeEnum.LOCAL.getCode(), ActivityProductTypeEnum.CROSS_REGION.getCode()));
                                        Integer orderStatus = orderInfo.getOrderStatus();
                                        Byte orderType = orderInfo.getOrderType();
                                        // 计算时间差
                                        Duration duration = Duration.between(orderInfo.getUpdateTime().toInstant(), new Date().toInstant());
                                        // 输出相差的分钟数
                                        long minutes = duration.toMinutes();
                                        if (orderStatus.equals(OrderStatusEnum.COMPLETED.getStatus()) || orderStatus.equals(OrderStatusEnum.CANCEL.getStatus())) {
                                            //已完成或者已经取消的就不用提醒了
                                            // 移除该队列的值,避免重复消费
                                            redisTemplate.opsForZSet().remove(ServicePrefixEnum.SAME_CITY + "." + DELAY_MESSAGE_QUEUE, value);
                                        } else {
                                            if (!ObjectUtils.isEmpty(orderType)) {
                                                pricingList.forEach(pricing -> {
                                                    if (orderType.equals(pricing.getProductType())) {
                                                        if (minutes >= pricing.getTimeoutReminderTime()) {
                                                            //去提醒
                                                            orderService.sendFsOvertimeNoticeMsg(orderId);
                                                            // 移除该队列的值,避免重复消费
                                                            redisTemplate.opsForZSet().remove(ServicePrefixEnum.SAME_CITY + "." + DELAY_MESSAGE_QUEUE, value);
                                                        }
                                                    }
                                                });

                                            }

                                        }
                                    }

                                }
                            }
                        }
                    }

                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (!ObjectUtils.isEmpty(lock)) {
                // 释放锁
                lock.unlock();
            }
        }

    }


    /**
     * 消息出队
     * 权重就是时间戳
     */
    @Scheduled(cron = "0/30 * * * * ? ")
    public void pullQueue2() {
        System.out.println("------------等待消费--------------" + simpleDateFormat.format(System.currentTimeMillis()));
        // 获取0-当前时间戳的范围的所有值
        Set<String> set = redisTemplate.opsForZSet().rangeByScore(ServicePrefixEnum.SAME_CITY + "." + DELAY_MESSAGE_QUEUE, 0, System.currentTimeMillis());
        Iterator<String> iterator = set.iterator();
        while (iterator.hasNext()) {
            String value = iterator.next();
            if (value.startsWith(ServicePrefixEnum.SAME_CITY.name())) {
                // 遍历取出每一个score
                Double score = redisTemplate.opsForZSet().score(ServicePrefixEnum.SAME_CITY + "." + DELAY_MESSAGE_QUEUE, value);
                if (!ObjectUtils.isEmpty(score)) {
                    // 达到时间进行消费 当前时间大于
                    if (System.currentTimeMillis() > score) {
                        if (value.contains(ServicePrefixEnum.SAME_CITY + RedisPrefixKey.UPDATE_RIDER_COORDINATES)) {
                            log.info("消费了" + value + "消费时间 " + simpleDateFormat.format(System.currentTimeMillis()));
                            String errandOrderSn = value.replace(ServicePrefixEnum.SAME_CITY + RedisPrefixKey.UPDATE_RIDER_COORDINATES, "");
                            ErrandOrder errandOrder = errandOrderRest.getByErrandOrderSn(errandOrderSn);
                            Date date = new Date();
                            if (!ObjectUtils.isEmpty(errandOrder)) {
                                BigDecimal oldPricePaid = errandOrder.getPricePaid();
                                if (ObjectUtils.isEmpty(oldPricePaid)) {
                                    JSONObject jsonObject1 = sysTcRest.getOrderInfo(errandOrderSn);
                                    if (!ObjectUtils.isEmpty(jsonObject1)) {
                                        BigDecimal totalPrice = jsonObject1.getBigDecimal("total_price");
                                        Double deliveryDistance = jsonObject1.getDouble("delivery_distance_meter");
                                        BigDecimal totalPaymentAmount = jsonObject1.getBigDecimal("total_pay_money");
                                        BigDecimal pricePaid = jsonObject1.getBigDecimal("real_pay_money");
                                        String pickUpCode = jsonObject1.getString("pickup_code");
                                        String receiptCode = jsonObject1.getString("complete_code");
                                        Byte paymentMethod = jsonObject1.getByte("settlement_type");
                                        BigDecimal totalCouponAmount = jsonObject1.getBigDecimal("coupons_total_fee");
                                        errandOrder.setTotalPrice(totalPrice);
                                        errandOrder.setDeliveryDistance(deliveryDistance);
                                        errandOrder.setPaymentMethod(paymentMethod);
                                        errandOrder.setTotalPaymentAmount(totalPaymentAmount);
                                        errandOrder.setPricePaid(pricePaid);
                                        errandOrder.setTotalCouponAmount(totalCouponAmount);
                                        errandOrder.setPickUpCode(pickUpCode);
                                        errandOrder.setReceiptCode(receiptCode);
                                        errandOrder.setUpdateTime(date);
                                        errandOrderMapper.updateById(errandOrder);
                                    }
                                }

                                //获取新的骑手坐标
                                JSONObject jsonObject = sysTcRest.getRiderLatestPosition(errandOrderSn);
                                if (!ObjectUtils.isEmpty(jsonObject)) {
                                    Double longitude = jsonObject.getDouble("rider_lng");
                                    Double latitude = jsonObject.getDouble("rider_lat");
//                                    Date updateTime = new Date(jsonObject.getLong("upload_time"));
                                    errandOrder.setLongitude(longitude);
                                    errandOrder.setLatitude(latitude);
                                    errandOrder.setUpdateTime(date);
                                    errandOrderMapper.updateById(errandOrder);
                                }
                                String orderSn = errandOrder.getOrderSn();
                                QueryWrapper<OrderInfo> wrapper = new QueryWrapper<>();
                                wrapper.lambda().eq(OrderInfo::getTcWaybillNo, orderSn);
                                OrderInfo orderInfo = orderInfoMapper.selectOne(wrapper);
                                if (!ObjectUtils.isEmpty(orderInfo)) {
                                    Integer orderStatus = orderInfo.getOrderStatus();
                                    if (!orderStatus.equals(OrderStatusEnum.DOOR_TO_DOOR_PICKUP.getStatus()) && !orderStatus.equals(OrderStatusEnum.TO_BE_DISPATCHED.getStatus())) {
                                        //不是上门取件也不是上门派送就不需要更新骑手坐标了
                                        // 移除该队列的值,避免重复消费
                                        redisTemplate.opsForZSet().remove(ServicePrefixEnum.SAME_CITY + "." + DELAY_MESSAGE_QUEUE, value);
                                    }
                                }
                            } else {
                                // 移除该队列的值,避免重复消费
                                redisTemplate.opsForZSet().remove(ServicePrefixEnum.SAME_CITY + "." + DELAY_MESSAGE_QUEUE, value);
                            }
                        }
                    }
                }
            }

        }
    }

}

